<template>
    <div class="user-div">
        <!-- 搜索工具栏 -->
        <el-row>
            <el-col :span="2">角色名：</el-col>
            <el-col :span="3">
                <el-input v-model="formParams.roleName" placeholder="查询目录名" clearable/>
            </el-col>
            <el-col :span="13">
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="success" @click="handleInsert">新增</el-button>
            </el-col>
        </el-row>

        <!--  显示数据的表格 -->
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center"/>
            <el-table-column prop="roleId" label="角色ID" width="80"/>
            <el-table-column prop="roleName" label="角色名" width="150"/>
            <el-table-column prop="remark" label="角色描述" width="150"/>
            <el-table-column align="right">
                <template #default="scope">
                    <el-button size="small" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page-div">
            <el-pagination layout="prev, pager, next"
                           :total="pageBean.total"
                           v-model:current-page="pageBean.currentPage"
                           v-model:page-size="pageBean.pageSize"
                           :page-sizes="[1, 2, 3, 4]"
                           @change="changePage"></el-pagination>
        </div>
    </div>

    <!-- 弹出框 -->
    <el-dialog :title="title" v-model="dialogFormVisible">
        <el-form :model="userForm" :rules="rules" ref="userFormBean">
            <el-form-item label="角色名" :label-width="formLabelWidth" prop="menuName">
                <el-input v-model="userForm.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth">
                <el-input v-model="userForm.remark" autocomplete="off"></el-input>
            </el-form-item>
            <el-tree ref="treeRef"
                    style="max-width: 600px"
                    :data="treeData"
                    show-checkbox
                    node-key="menuId"
                    :props="menuProps"
            />
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(userFormBean)">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>

    import {onMounted, ref, reactive, watch} from "vue";
    import axios from '@/api/index.js'
    import {ElMessage, ElMessageBox} from "element-plus";
    import {clearObject} from "../../common/util";
    import {jsonToTree} from "../../common/util"

    const tableData = ref([]);

    onMounted(() => {
        handleSearch()
        getTree()
    })

    //分页控制
    const pageBean = reactive({
        pageSize: 10,
        currentPage: 1,
        total: 0
    })

    const changePage = (currentPage, pageSize) => {
        pageBean.currentPage = currentPage
        pageBean.pageSize = pageSize
        handleSearch()
    }


    //查询操作
    let formParams = reactive({
        menuName: '',
        menuUrl: ''
    })

    const handleSearch = () => {
        axios.post("/role/list", {...pageBean, ...formParams}).then(response => {
            if (response.data.code === 200) {
                tableData.value = response.data.data.list
                pageBean.total = response.data.data.total
            } else {
                ElMessage.error(response.data.message)
            }

        })
    }

    //获得完整的树
    const treeRef = ref();
    const treeData = ref()
    const menuProps = ref({
        label: 'menuName',
        children: 'menus'
    })
    const getTree = () => {
        axios.post("/menu/allList", {}).then(response => {
            if (response.data.code === 200) {
                treeData.value = jsonToTree(response.data.data)
            } else {
                ElMessage.error(response.data.message)
            }

        })
    }

    //删除操作
    const handleDelete = (row) => {
        ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            axios.post("/role/delete/" + row.roleId)
                .then(response => {
                    if (response.data.code === 200) {
                        ElMessage.success('删除成功!');
                        handleSearch()
                    } else {
                        ElMessage.error(response.data.message)
                    }
                })
        }).catch(() => {
            ElMessage.error("取消删除")
        });

    }


    /**------------ 添加操作 ------------*/
    const dialogFormVisible = ref(false)
    const formLabelWidth = '140px'
    const title = ref('添加角色')
    let userForm = reactive({
        roleId: 0,
        roleName: '',
        remark: '',
    })

    const handleInsert = () => {
        title.value = '添加角色'
        dialogFormVisible.value = true
        treeRef.value.setCheckedKeys([])
        clearObject(userForm)
    }

    const rules = reactive({
        roleName: [
            {required: true, message: '角色不能为空！', trigger: 'blur'},
            {pattern: /^\w{3,10}$/, message: '角色格式不正确！', trigger: 'blur'},
        ],
    })


    /**------------ 编辑操作 ------------*/
    const handleEdit = (row) => {
        userForm = row;
        title.value = "编辑角色"
        //获得角色对应的菜单
        axios.get("/menu/roleList/" + row.roleId)
            .then(response => {
                if (response.data.code === 200) {
                    //选择操作
                    let checkMenuId = response.data.data.map(item => item.menuId)
                    treeRef.value.setCheckedKeys(checkMenuId)
                } else {
                    ElMessage.error(response.data.message)
                }
            })
        dialogFormVisible.value = true
    }

    /**------------ 提交表单 ------------*/
    const userFormBean = ref();
    const handleSubmit = (userForms) => {
        userForms.validate((valid, fields) => {
            if (valid) {
                let option = {
                    method: 'post',
                    url: '/role/insert',
                    data: {...userForm,menuIds:[...treeRef.value.getHalfCheckedKeys(),...treeRef.value.getCheckedKeys()]}
                }
                if (title.value === '编辑角色') {
                    option.url = '/role/update'
                }
                console.log(option.data)
                axios(option)
                    .then(response => {
                        dialogFormVisible.value = false
                        handleSearch()
                    })
                    .catch(error => {
                        console.log(error)
                    });
            }
        })
    }

    // const ids = ref([])
    // //复选框操作
    // const handleSelectionChange = (val) => {
    //     console.log(val)
    //     ids.value = val.map(item => item.userId)
    // }
    // //批量删除
    // const handleDeleteAll = () => {
    //     ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning'
    //     }).then(() => {
    //         axios.delete("/menu/delete/" + ids.value)
    //             .then(response => {
    //                 if (response.data.code === 200) {
    //                     ElMessage.success('删除成功!');
    //                     handleSearch()
    //                 } else {
    //                     ElMessage.error(response.data.message)
    //                 }
    //             })
    //     }).catch(() => {
    //         ElMessage.error("取消删除")
    //     });
    // }
</script>
<style scoped>
    .user-div {
        background-color: #ffffff;
        height: 100%;
    }

    .el-row {
        height: 60px;
        line-height: 60px;
    }

    .el-pagination {
        margin: 10px auto;
    }

    .page-div {
        display: flex;
    }
</style>
